package com.example.uniappspringbootstartweb.controller;

import com.example.uniappspringbootstartweb.DTO.UserDTO;
import com.example.uniappspringbootstartweb.DTO.nicheng;
import com.example.uniappspringbootstartweb.entity.User;
import com.example.uniappspringbootstartweb.service.UserService;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

/**
 * Created by lilijava
 * on 2024/12/28
 * <p>
 * on  uni-app-springboot-start-web
 */

@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/api/auth")
public class UserController {
    @Autowired
    private UserService userService;



    /**
     * 处理用户注册请求
     */
    @PostMapping("/register")
    public ResponseEntity<String> handleRegister(@Valid @RequestBody UserDTO userDTO, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return new ResponseEntity<>("Validation failed", HttpStatus.BAD_REQUEST);
        }
        try {
            userService.registerUser(userDTO);
            return new ResponseEntity<>("User registered successfully", HttpStatus.CREATED);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); // 用户名已存在时返回409 Conflict
        }
    }
    @GetMapping ("/profile")
    public ResponseEntity<nicheng> kitchening(Integer id) {
        User user= userService.findById(Long.valueOf(id));

        nicheng nicheng=new nicheng(user.getNichen(),user.getImg());
        return  ResponseEntity.ok(nicheng);
    }
    @GetMapping("/user-id")
    public Long getUserId(HttpSession session) {
        String sessionId = session.getId();
        System.out.println("Current session ID: " + sessionId);
        Object userIdObj = session.getAttribute("userId");
        if (userIdObj == null) {
            System.out.println("Session user ID is null.");
        } else {
            System.out.println("Session user ID: " + userIdObj);
        }
        return (Long) userIdObj;
    }
    /**
     * 处理用户登录请求
     */
    @PostMapping("/login")
    public ResponseEntity<String> handleLogin(@Valid @RequestBody UserDTO userDTO, BindingResult bindingResult, HttpSession session) {
        if (bindingResult.hasErrors()) {
            return new ResponseEntity<>("Validation failed", HttpStatus.BAD_REQUEST);
        }
        try {
            // Authenticate the user and find the corresponding user object
            User authenticatedUser = userService.authenticateUser(userDTO);

            // Assuming authenticateUser returns a User object, extract the ID from it.
            Long userId = authenticatedUser.getId(); // 假设User类有一个getId()方法
            // Set the userId attribute in the session
            session.setAttribute("userId", userId);
            // Debugging output
            System.out.println("Logged in user ID: " + userId);
            System.out.println("Session user ID: " + session.getAttribute("userId"));
            System.out.println("Are they equal? " + userId.equals(session.getAttribute("userId")));
            return new ResponseEntity<>("Login successful", HttpStatus.OK);
        } catch (Exception e) { // 使用更广泛的异常类型或具体异常类型
            return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED); // 登录失败时返回401 Unauthorized
        }
    }
}
